package com.example.zwh.computershop.shopping_cart;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.zwh.computershop.Myapp;
import com.example.zwh.computershop.R;
import com.example.zwh.computershop.sqlModel.Cart;
import com.example.zwh.computershop.sqlModel.Product;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import static android.content.ContentValues.TAG;

public class ShoppCar_Fragment extends Fragment {

    private static ShopAdapter shopAdapter;
    public static List<Shop> shopList = new ArrayList<>();
    RecyclerView recyclerView;

    private TextView mTitle;
    private Button mManage;
    private Button mOK;

    private static CheckBox AllSel;
    private TextView mTotal;
    private static TextView money;
    private Button mBuy;
    private Button mDel;
    private LinearLayout mLLEmpty;
    private Myapp myapp;

    private boolean hide = false;

    private static double allMoney = 0.0;

    public ShoppCar_Fragment() {
        hide = false;
        Log.d(TAG, "ShoppCar_Fragment: 构造函数");
    }

    //初始化数据
    private void init() {
        shopList.clear();

        for (Cart i : myapp.getCart())
            for (Product j : myapp.getProducts()) {
                if (i.getProductId().equals(j.getProductId())) {
                    shopList.add(new Shop(i.getProductId(), j.getBrand(), j.getProductName(), j.getImgUrl(), j.getPrice(), i.getAddNum()));
                }
            }
        Log.d(TAG, "initxxx: " + myapp.getCart().size() +" "+ shopList.size());
    }

    //判断购物车是否为空
    private void showData() {
        if (shopList.size() == 0) {
            initEmptyView();           //如果数据为空,显示空的试图
            return;
        }
    }

    //显示购物车为空
    private void initEmptyView() {
        recyclerView.setVisibility(View.GONE);
        mLLEmpty.setVisibility(View.VISIBLE);
        Log.d(TAG, "initEmptyView: hello");
    }

    //点击管理按钮和完成按钮
    private void setHide() {
        if (hide) {
            mManage.setVisibility(View.GONE);
            mBuy.setVisibility(View.GONE);
            money.setVisibility(View.GONE);
            mTotal.setVisibility(View.GONE);
            ShopAdapter.setIsManage(hide);
            mOK.setVisibility(View.VISIBLE);
            mDel.setVisibility(View.VISIBLE);
        } else{
            mOK.setVisibility(View.GONE);
            mDel.setVisibility(View.GONE);
            ShopAdapter.setIsManage(hide);
            mTotal.setVisibility(View.VISIBLE);
            mManage.setVisibility(View.VISIBLE);
            mBuy.setVisibility(View.VISIBLE);
            money.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        init();
        shopAdapter.notifyDataSetChanged();
    }

    //得到商品总价格（勾选）
    private static double getMoney() {
        allMoney = 0.0;
        for (Shop i : shopList) {
            if (i.getmCheckBox())
                allMoney += i.getPrice() * i.getNum();
        }
        return allMoney;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        myapp = (Myapp) getActivity().getApplication();
        if (myapp.getLoState() == 1) {
            init();
        } else return;
        if (shopAdapter == null) {
            Log.d(TAG, "onViewCreated: 第一次到界面");
        } else {
            if (myapp.getUser() != null) {
                Log.d(TAG, "onViewCreated: 不是第一次到界面");
                hide = false;
                shopAdapter.notifyDataSetChanged();
            }

        }

    }

    private void alterCart() {
        for (Shop s : shopList)
            for (Cart c : myapp.getCart()) {
                if (s.getProductId().equals(c.getProductId()) && s.getNum() != c.getAddNum() && myapp.getUser().getId() == c.getId()) {
                    c.setAddNum(s.getNum());
                    SQLoperation.modifyCart(c);
                }
            }
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mLLEmpty = getActivity().findViewById(R.id.ll_empty);
        mTitle = getActivity().findViewById(R.id.tv_shop_car_title);
        mTitle.setText("购物车(" + getLength() +")");
        mManage = getActivity().findViewById(R.id.btn_shop_car_mag);
        mManage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hide = true;
                setHide();
                renovate();
            }
        });
        mOK = getActivity().findViewById(R.id.btn_shop_car_ok);
        mOK.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hide = false;
                setHide();
                //修改数据库内容
                alterCart();
                renovate();
            }
        });
        mBuy = getActivity().findViewById(R.id.btn_shop_car_buy);
        mBuy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), shopcar_order.class);
                Bundle bundle = new Bundle();
                int j = 0;
                for (Shop i : shopList) {
                    if (i.getmCheckBox()) {
                        bundle.putString(String.valueOf(j), i.getProductId());
                        j++;
                    }
                }
                intent.putExtras(bundle);
                if (j == 0) {
                    Toast.makeText(getContext(), "订单不能为空", Toast.LENGTH_SHORT).show();
                } else {
                    startActivity(intent);
                }
                Log.d(TAG, "onClickdingdan: ");
            }
        });
        mDel = getActivity().findViewById(R.id.btn_shop_car_del);
        mDel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Iterator<Shop> shop = shopList.iterator();
                Iterator<Cart> cart = myapp.getCart().iterator();
                while (shop.hasNext()) {
                    Shop value = shop.next();
                    if (value.getmCheckBox()) {
                        while (cart.hasNext()) {
                            Cart c = cart.next();
                            if (c.getProductId().equals(value.getProductId())  && myapp.getUser().getId() == c.getId()) {
                                SQLoperation.deleteCart(c);
                                shop.remove();
                                cart.remove();
                                Log.d(TAG, "deleteCart: 删除成功");
                            }
                        }
                    }
                }
                showData();
                mTitle.setText("购物车:(" + getLength() +")");
                renovate();
            }
        });
        mTotal = getActivity().findViewById(R.id.tv_shop_car_text);
        money = getActivity().findViewById(R.id.tv_shop_car_m);
        AllSel = getActivity().findViewById(R.id.cb_shop_car_allsel);
        AllSel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //点击全选
                CheckBox all = (CheckBox)v;
                if (all.isChecked())
                    ShopAdapter.allSelect(true);
                else
                    ShopAdapter.allSelect(false);
                renovate();
            }
        });

        recyclerView = getActivity().findViewById(R.id.rlv_shop_car_list);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        shopAdapter = new ShopAdapter(getContext(), shopList);
        shopAdapter.isManage = false;
        recyclerView.setAdapter(shopAdapter);
        showData();
        renovate();
    }

    public void renovate() {
        setAllMoney(getMoney());
        shopAdapter.notifyDataSetChanged();
    }

    public static void myAllCheckBoxChange() {
        AllSel.setChecked(false);
    }

    public static void setAllMoney(double allMoney) {
        money.setText("￥" + allMoney);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_shopp_car, container, false );
    }

    private int getLength() {
        return shopList.size();
    }

}
